<?php
/**
 * 提现模型
 * User: wuhao
 * Date: 2017/5/8
 * Time: 17:54
 */
namespace app\backend\model;

use think\Model;

class Withdraw extends Model
{
    private $_withdrawTable = 'z_withdraw';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 新增提现申请记录
     * @date   2017-05-08
     * @author wuhao
     *
     * @param $mid 提现申请的用户id
     * @param $moneyFen  提现金额(分)
     * @param $bankFee   提现手续费率(千分之几)
     * @param $accountType 账号类型 0=银行 1=支付宝
     * @param $bankName 银行名称
     * @param $bankCode 银行代码
     * @param $account 账号
     *
     * @return array|bool
     */
    public function addRecord($mid, $moneyFen, $bankFee, $accountType, $bankName, $bankCode, $account)
    {
        if (!is_numeric($moneyFen) || $moneyFen < 0 || !is_numeric($bankFee) || $bankFee < 0 || !in_array($accountType, [0, 1]) || !$account || !$mid) {
            return false;
        }
        if ($accountType == 0 && (!$bankCode || !$bankName)) {//银行卡需要判断什么银行，支付宝不需要
            return false;
        }
        $serviceMoneyFen = round($moneyFen * $bankFee / 1000); //手续费
        $serviceMoneyFen = $serviceMoneyFen < 100 ? 100 : $serviceMoneyFen;//不足一元按一元算
        $actualMoneyFen  = $moneyFen - $serviceMoneyFen;       //实际提现费用

        $moneyYuan        = yuan($moneyFen);
        $actualMoneyYuan  = yuan($actualMoneyFen);
        $serviceMoneyYuan = yuan($serviceMoneyFen);

        //添加备注信息
        $memo = "申请提现金额:{$moneyYuan}元,手续费:{$serviceMoneyYuan}元,实际提现金额:{$actualMoneyYuan}元";
        $memo .= "【{$account}({$bankName})】";

        //添加统一虚拟的订单ID - 使用毫秒
        $orderId = 'wd_' . str_replace('.', '', microtime(true));
        $data    = [
            'mid'           => $mid,
            'orderid'       => $orderId,
            'money'         => $moneyFen,
            'actual_money'  => $actualMoneyFen,
            'service_money' => $serviceMoneyFen,
            'bank_fee'      => $bankFee,
            'apply_time'    => date('Y-m-d H:i:s'),
            'bank_name'     => $bankName,
            'bank_code'     => $bankCode,
            'account'       => $account,
            'type'          => $accountType,
            'memo'          => $memo,
            'status'        => 0
        ];
        $this->startTrans();
        $res = $this->setTable($this->_withdrawTable)->insertGetId($data);
        if (!$res) {
            $this->rollback();
            return ['code' => 402, 'msg' => $this->getLastSql()];
        }

        //交易流水
        $memberModel = new Member();
        $res = $memberModel->withdrawMoneyModify($mid, ADMIN, $actualMoneyFen, $serviceMoneyFen, $res,  $orderId,  $moneyFen, $account, $bankName);
        if ($res['code'] != 200) {
            return ['code' => $res['code'], 'msg' => $res['msg']];
        } else {
            $this->commit();
            return ['code' => 200, 'msg' => 'ok'];
        }
    }

    /**
     * 获取某用户未处理的提现金额总数
     * @date   2017-05-10
     * @author wuhao
     *
     * @param $mid 提现申请的用户id
     *
     * @return bool
     */
    public function getUntreatedWithdraw($mid)
    {
        if (!$mid) {
            return false;
        }
        $where = ['mid' => $mid, 'status' => 0];
        $field = 'SUM(money) as money';
        $res =  $this->setTable($this->_withdrawTable)->field($field)->where($where)->group('mid')->find();
        return $res ? $res['money'] : 0;
    }

    /**
     * 获取提现申请列表
     * @date   2017-05-10
     * @author wuhao
     *
     * @param $memberId 提现申请的用户id
     * @param $dtype    用户类型
     * @param $status   提现状态 -1全部 0=提现中（未处理） 1=提现成功  2=拒绝提现  3=提现失败(处理了，但出现了xx问题)
     * @param $searchType 搜索类型  0=按用户名 1=按平台账号
     * @param $content  搜索内容
     * @param $page     页数
     * @param $pageSize 每页个数
     *
     * @return bool
     */
    public function getWithdrawList($memberId, $dtype, $status, $searchType, $content, $page, $pageSize)
    {
        if (!is_numeric($memberId) || !is_numeric($dtype) || !in_array($status, [-1,0,1,2,3]) || !is_numeric($page) || !is_numeric($pageSize)) {
            return false;
        }
        $where = [];
        if ($status != -1) {
            $where['status'] = $status;
        }
        if ($dtype == 0) {//管理员
            if ($content) {
                $searchType == 0 ? ($map['nickname'] = ['like', "%$content%"]) : ($map['username'] = $content);
                $memberModel = new Member();
                //获取会员信息
                $mInfo = $memberModel->getMemberInfo($map, 'id');
                if ($mInfo) {
                    $midArr = array_column($mInfo, 'id');
                    $where['mid'] = ['in', $midArr];
                } else {//没有的话返回为空
                    return [];
                }
            }
        } else {//其他用户
            $where['mid'] = $memberId;
        }
        $res = $this->setTable($this->_withdrawTable)->where($where)->order('id desc')->page($page, $pageSize)->select();
        if ($res) {
            $count = $this->setTable($this->_withdrawTable)->where($where)->count();
            $total = ceil($count / $pageSize);
            $data = [
                'list' => $res,
                'total' => $total,
            ];
        } else {
            $data = [];
        }
        return $data;
    }

    /**
     * 根据id获取提现记录详情
     * @date   2017-05-11
     * @author wuhao
     *
     * @param $id 提现记录id
     *
     * @return array
     */
    public function getWithdrawById($id, $field = '*')
    {
        if (!is_numeric($id) || $id<=0) {
            return false;
        }
        return $this->setTable($this->_withdrawTable)->field($field)->find($id);
    }


    /**
     * 根据提现账户获取提现申请的列表
     * @date   2017-05-12
     * @author wuhao
     *
     * @param $account 提现账户
     * @param $status  -1=全部，0=未处理, 1=提现成功,2=拒绝提现,3=提现失败
     * @param $field   获取的字段
     *
     * @return array
     */
    public function getListByAccount($account, $status = -1, $field = '*')
    {
        if (!$account || !in_array($status, [-1,0,1,2,3]) || !$field) {
            return false;
        }
        $where['account'] = $account;
        if ($status != -1) {
            $where['status'] = $status;
        }
        $res = $this->setTable($this->_withdrawTable)->field($field)->where($where)->select();
        return $res ?: [];
    }

}